package org.lwj.logger.clazz;

import org.lwj.logger.util.Util;

/**
 * 对象实例化
 * 
 * @author liwenjian
 *
 */
public class Clazz<T> {

	/**
	 * 对象
	 */
	private T object;

	public Clazz(T object) throws Exception {
		if (object == null) {
			throw new Exception("object is null");
		}
		setObject(object);
	}

	public T getObject() {
		return object;
	}

	public void setObject(T object) {
		this.object = object;
	}

	/**
	 * 如果依赖类已加载, 则实例化对象
	 * 
	 * @param dependClassName 依赖类的类名
	 * @param objectClassName 对象类的类名
	 * @return
	 */
	public static Clazz<Object> newInstance(String dependClassName, String objectClassName) {
		Clazz<Object> clazz = null;
		try {
			if (Util.isClassLoaded(dependClassName)) {
				Class<?> objectClass = Class.forName(objectClassName);
				Object object = objectClass.newInstance();
				clazz = new Clazz<Object>(object);
			}
		} catch (Throwable e) {
		}
		return clazz;
	}

	/**
	 * 如果依赖类已加载, 则实例化对象
	 * 
	 * @param <T>
	 * @param objectType      对象类型
	 * @param dependClassName 依赖类的类名
	 * @param objectClassName 对象类的类名
	 * @return
	 */
	public static <T> Clazz<T> newInstance(Class<T> objectType, String dependClassName, String objectClassName) {
		Clazz<Object> clazzObj = newInstance(dependClassName, objectClassName);
		Clazz<T> clazz = toType(objectType, clazzObj);
		return clazz;
	}

	/**
	 * 类型转换
	 * 
	 * @param <T>
	 * @param objectType 对象类型
	 * @param clazzObj   被转换Clazz
	 * @return
	 */
	public static <T> Clazz<T> toType(Class<T> objectType, Clazz<?> clazzObj) {
		Clazz<T> clazz = null;
		try {
			if (objectType == null || clazzObj == null) {
				return clazz;
			}
			Object object = clazzObj.getObject();
			if (object != null && objectType.isAssignableFrom(object.getClass())) {
				@SuppressWarnings("unchecked")
				T t = (T) object;
				clazz = new Clazz<T>(t);
			}
		} catch (Throwable e) {
		}
		return clazz;
	}

}
